package com.koylu.validator;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.digester.Digester;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ValidatorManager {
	
	private static Log logger    = null;
	private Validator  validator = null;
	private Map ruleCache = null;
	
	public ValidatorManager() {
		validator = new Validator();
		logger = LogFactory.getLog(getClass());
		ruleCache = new HashMap();
	}
	
	public Rule findRule(String name){
		Rule rule = null;
		if(ruleCache.containsKey(name)){
			rule = (Rule)ruleCache.get(name);
		}else{
			rule = validator.findRule(name);
			ruleCache.put(name, rule);
		}
		return rule;
	}

	public Validator getValidator() {
		return validator;
	}

	public void setValidator(Validator validator) {
		this.validator = validator;
	}
	
	public synchronized void addValidator(InputStream configStream) throws Exception{			
		Digester digester = new Digester();		
		digester.addObjectCreate("validator",Validator.class);		
		digester.addObjectCreate("validator/rule",Rule.class);
		digester.addSetProperties("validator/rule","name","name");
		digester.addSetProperties("validator/rule","classname","classname");
		digester.addSetProperties("validator/rule","method","method");
		digester.addSetProperties("validator/rule","msg","msg");
		digester.addSetNext("validator/rule","addRule");		
		digester.addObjectCreate("validator/rule/parameters/parameter",Parameter.class);
		digester.addSetProperties("validator/rule/parameters/parameter","type","type");
		digester.addSetProperties("validator/rule/parameters/parameter","key","key");
		digester.addSetNext("validator/rule/parameters/parameter","addParameter");			
		Validator validator = ((Validator)digester.parse(configStream));
		for (Iterator iterator = validator.getRules().iterator(); iterator.hasNext();) {
			Rule rule = (Rule) iterator.next();
			try {
				this.validator.addRule(rule);	
			} catch (Exception e) {
				logger.error(e);
			}			
		}
	}
	
	public String toString() {
		return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
	}	
}
